package com.hutao.chargingpile.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.hutao.chargingpile.oss.service.FileService;
import com.hutao.chargingpile.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(InputStream inputStream, String module, String fileName) {
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
        // 判断BUCKET_NAME是否存在
        if(!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        String timeFolder = new DateTime().toString("/yyyy/MM/dd/");
        // 文件名生成
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));

        String info = module + timeFolder + fileName;
        PutObjectRequest putObjectRequest = new PutObjectRequest(OssProperties.BUCKET_NAME, info, inputStream);
        putObjectRequest.setProcess("true");
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        return "https://"+OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + info;
    }

    @Override
    public void removeFile(String url) {
        String host = "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/";
        String info = url.substring(host.length());
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
        System.out.println(OssProperties.BUCKET_NAME+info);
        ossClient.deleteObject(OssProperties.BUCKET_NAME, info);
        ossClient.shutdown();
    }
}
